package com.thinkgem.jeesite.modules.erp.web;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.exception.CustomException;
import com.thinkgem.jeesite.common.utils.TimeUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.erp.entity.Department;
import com.thinkgem.jeesite.modules.erp.entity.Goods;
import com.thinkgem.jeesite.modules.erp.entity.OutAndInWarehouseOrder;
import com.thinkgem.jeesite.modules.erp.entity.Page;
import com.thinkgem.jeesite.modules.erp.entity.Repository;
import com.thinkgem.jeesite.modules.erp.service.WareHouseService;
import com.thinkgem.jeesite.modules.oa.entity.Leave;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 出入库仓库管理
 * @author lx
 */
@Controller
@RequestMapping(value = "${adminPath}/erp/warehouse")
public class WarehouseController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final String HeadOffice="1";//总公司编号

	@Autowired
	private WareHouseService wareHouseService;
	//去入库
	@RequestMapping(value = {"putIn"})
	public String storage(Model model) throws JsonProcessingException {
//		Department dep = wareHouseService.queryAllDepsWorkers(HeadOffice);
		ObjectMapper om = new ObjectMapper ();
//		String depstr = om.writeValueAsString (dep).replaceAll("name", "text");
		User user = UserUtils.getUser();
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("id", user.getId());
		map.put("text", user.getName());
		map.put("selected", true);
		String depstr2 = om.writeValueAsString (map);
		model.addAttribute("WorkersData", depstr2);
		model.addAttribute("WorkersData2", depstr2);
		//查询所有公司下面所有的部门和员工
		model.addAttribute("Global", new Global());
		return "modules/erp/putIn";
	}
	//去出库
	@RequestMapping(value = {"takeOut"})
	public String outBound(Model model) throws JsonProcessingException {
		Department dep = wareHouseService.queryAllDepsWorkers(HeadOffice);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (dep).replaceAll("name", "text");
		model.addAttribute("WorkersData", depstr);
		User user = UserUtils.getUser();
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("id", user.getId());
		map.put("text", user.getName());
		String self=om.writeValueAsString (map);
		model.addAttribute("Self", self);
		model.addAttribute("Global", new Global());
		return "modules/erp/takeOut";
	}

	//统计查询--物品统计
	@RequestMapping(value={"statisticsGoods"})
	public String statisticsGoods(){
		return "modules/erp/toStatisticsGoods";
	}
	
	@RequestMapping(value={"queryGoodsType"})
	public String queryGoodsType(){
		
		return null;
	}
	//模糊查询出货物
	@ResponseBody
	@RequestMapping(value={"dimQueryGoods"})
	public String dimQueryGoods(HttpServletRequest request) throws JsonProcessingException, UnsupportedEncodingException{
		String keyword = request.getParameter("key");
		List<Goods>list=null;
		if(null!=keyword&&!"".equals(keyword)){
			keyword=java.net.URLDecoder.decode(keyword,"UTF-8");
			//通过关键字模糊查询物品名称或物品编号
			list=wareHouseService.dimQueryGoods(keyword);
		}
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		return depstr;
	}
	
	
	//入库
	@ResponseBody
	@RequestMapping(value={"acceptMerchandise"},method = RequestMethod.POST)
	public String acceptMerchandise(OutAndInWarehouseOrder op,HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
		String time = op.getTime();
		
		if(null!=time&&!"".equals(time)){
			op.setTime(TimeUtils.EasyUITimeFormat(time));
		}
		try {
			wareHouseService.bePutInStorage(op);
		} catch (Exception e) {
			logger.error("入库失败：", e);
			addMessage(redirectAttributes, "系统内部错误！");
			return "0";
		}
		
		return "1";
	}
	
	//出库
	@ResponseBody
	@RequestMapping(value={"takeOutMerchandise"},method = RequestMethod.POST)
	public String takeOutMerchandise(OutAndInWarehouseOrder op,RedirectAttributes redirectAttributes) throws ParseException{
		op.setTime(TimeUtils.EasyUITimeFormatRightNow());
		try {
			wareHouseService.beTakeOutStorage(op);
		} catch (Exception e) {
			logger.error("出库失败：", e);
			addMessage(redirectAttributes, "系统内部错误！");
			return "0";
		}
		return "1";
	}
	
	//查询物件库存数量是否充足
	@ResponseBody
	@RequestMapping(value={"isGoodsdEnough"},method = RequestMethod.POST)
	public String isGoodsdEnough(OutAndInWarehouseOrder op,RedirectAttributes redirectAttributes) throws ParseException, JsonProcessingException{
		List<Map<String,Object>>list =wareHouseService.isEnough(op);
		ObjectMapper om = new ObjectMapper ();
		String str = om.writeValueAsString (list);
		return str;
	}
	
	//去订单审核
	@RequestMapping(value={"toCheckOrder"})
	public String toCheckOrder(OutAndInWarehouseOrder order,Model model) throws JsonProcessingException{
		User user = UserUtils.getUser();
		order.setVerifier(user.getId());
		List<OutAndInWarehouseOrder> list=wareHouseService.getPersonalOrders(order);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		model.addAttribute("listOrders", depstr);
		return "modules/erp/toCheckOrder";
	}
	
	//去查询订单
	@RequestMapping(value={"queryOrders"})
	public String toQueryOrders(Model model) throws JsonProcessingException{
		Department dep = wareHouseService.queryAllDepsWorkers(HeadOffice);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (dep).replaceAll("name", "text");
		model.addAttribute("WorkersData", depstr);
		
		List<OutAndInWarehouseOrder> list=wareHouseService.queryRelevantOrders(null);
		String result = om.writeValueAsString (list);
		System.out.println(result);
		model.addAttribute("list", result);
		
		return "modules/erp/queryOrders";
	}
	
	
	//根据条件查询对应的内容(假分页，取消，但保留，该方法没有设置物料名称匹配)
	@RequestMapping(value={"queryRelevantOrders"})
	@ResponseBody
	public String queryRelevantOrders(OutAndInWarehouseOrder order) throws JsonProcessingException{
		List<OutAndInWarehouseOrder> list=wareHouseService.queryRelevantOrders(order);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		return depstr;
	}
	
	//根据条件查询对应的内容(真分页)存在错误
	/*@RequestMapping(value={"ajQueryOrders"})
	@ResponseBody
	public String ajQueryOrders(OutAndInWarehouseOrder order) throws JsonProcessingException{
		Page<OutAndInWarehouseOrder> page=wareHouseService.ajQueryOrders(order);
		ObjectMapper om = new ObjectMapper ();
 		String depstr = om.writeValueAsString (page);
 		if(null!=depstr){
 			depstr=depstr.replaceAll("code", "oCode").replaceAll("executor", "executorCode").replaceAll("time", "execDate")
 				.replaceAll("type", "oType").replaceAll("status", "oStatus")
 				.replaceAll("remarks", "details");
 		}
		return depstr;
	}*/
	
	
	//订单审核
	@RequestMapping(value={"ajMarking"})
	@ResponseBody
	public String ajMarking(@RequestParam String code,@RequestParam String action) throws JsonProcessingException{
		try {
			wareHouseService.Marking(code,action);
		} catch (CustomException e) {
			return "0";
		}
		return "1";
	}
	
	
	
	
	//查询返回所有的仓库信息
	@RequestMapping(value={"queryRepository"})
	@ResponseBody
	public String queryRepository(HttpServletRequest request) throws JsonProcessingException{
		String id="0";
		List<Repository>list = wareHouseService.queryRepositoryTree(id);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (list);
		if(null!=depstr&&!"".equals(depstr)){
			depstr=depstr.replaceAll("rep_Name", "text");
		}
		return depstr;
	}
	//分页查询出某个仓库下的物料信息
	
	
	//物件剩余查询
	@RequestMapping(value={"queryResidue"})
	public String queryResidue() throws JsonProcessingException{
		
		return "modules/erp/toQueryResidue";
	}
	
	
	
	//repository	查询
	@RequestMapping(value={"repository"})
	public String repository(Model model) throws JsonProcessingException{
		/*List<Repository> repos = wareHouseService.queryAllRepository();
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (repos);
		if(null!=depstr&&!"".equals(depstr)){
			depstr=depstr.replaceAll("rep_name", "text");
		}*/
		return "modules/erp/toRepository";
	}
	
	@RequestMapping(value={"toRightRepository"})
	public String toRightRepository(Model model,HttpServletRequest request){
		String repository = request.getParameter("repository");
		if(null!=repository&&!"".equals(repository)){
			
		}else{
			repository="0";
		}
		model.addAttribute("repository", repository);
		return "modules/erp/repositorys";
	}
	
	//repository	查询分页
	@RequestMapping(value={"repositoryPage"})
	@ResponseBody
	public String repositoryPage(HttpServletRequest request) throws JsonProcessingException{
		String page=request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String repository = request.getParameter("repository");
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("page", (Integer.parseInt(page)-1)*(Integer.parseInt(pageSize)));
		map.put("pageSize", pageSize);
		map.put("repository", repository);
		Integer amount = wareHouseService.queryRepositoryMaterialAmount(map);//总数量
		List<Map<String, Object>> repos =wareHouseService.queryRepositoryByPage(map);//当前需要的信息
		map.clear();
		map.put("total", amount);
		map.put("rows", repos);
		ObjectMapper om = new ObjectMapper ();
		String depstr = om.writeValueAsString (map);
		if(null!=depstr&&!"".equals(depstr)){
			depstr=depstr.replaceAll("rep_name", "text");
		}
		return depstr;
	}
	
	
	//repository	删除
	@RequestMapping(value={"repositoryDel"})
	@ResponseBody
	public String repositoryDel(Model model,HttpServletRequest request) throws JsonProcessingException{
		String repId = request.getParameter("repId");
		wareHouseService.deleteRepository(repId);
		return "1";
	}
	
	//repository	新增
	@RequestMapping(value={"repositoryAdd"})
	@ResponseBody
	public String repositoryAdd(Model model,HttpServletRequest request,Repository repository) throws JsonProcessingException{
		String resutlt=wareHouseService.addRepository(repository);
		String depstr = null;
		if(null!=resutlt){
			ObjectMapper om = new ObjectMapper ();
			depstr = om.writeValueAsString (resutlt);
		}
		return depstr;
	}
	@RequestMapping(value={"repositoryUpdate"})
	@ResponseBody
	public String repositoryUpdate(Repository repository) throws JsonProcessingException{
		String resutlt=wareHouseService.updateRepository(repository);
		String depstr = null;
		if(null!=resutlt){
			ObjectMapper om = new ObjectMapper ();
			depstr = om.writeValueAsString (resutlt);
		}
		return depstr;
	}
	
	@RequestMapping(value={"updateOrdersInfo"})
	@ResponseBody
	public String updateOrdersInfo(OutAndInWarehouseOrder op) throws JsonProcessingException{
		String result=wareHouseService.updateOrdersInfo(op);
		return result;
	}
	
	//异步获取当前订单编号次数
	@RequestMapping(value={"ordersTimes"})
	@ResponseBody
	public String ordersTimes(HttpServletRequest request,Model model) throws JsonProcessingException{
		String type = request.getParameter("type");//
		Map<String,Object>map=wareHouseService.ordersTimes(type);
		String index=null;
		if(null!=map){
			if("st".equals(type)){//入库
				index=String.format("%03d", Integer.parseInt((String)map.get("stindex"))+1);
			}else{
				index=String.format("%03d", Integer.parseInt((String)map.get("obindex"))+1);
			}
			ObjectMapper om = new ObjectMapper ();
			index = om.writeValueAsString (index);
		}
		return index;
	}
	@RequestMapping(value={"queryRepositoryName"})
	@ResponseBody
	public String queryRepositoryName(HttpServletRequest request) throws JsonProcessingException{
		String repository = request.getParameter("repository");
		String repoName=wareHouseService.queryRepositoryName(repository);
		ObjectMapper om = new ObjectMapper ();
		repoName = om.writeValueAsString (repoName);
		return repoName;
	}
	
	//入库4按钮
	@RequestMapping(value={"queryPutInOnlyOrders"})
	@ResponseBody
	public String queryPutInOnlyOrders(HttpServletRequest request) throws JsonProcessingException{
		String index = request.getParameter("index");
		String sort = request.getParameter("sort");
		User user = UserUtils.getUser();//当前用户
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("index", index);
		map.put("sort", sort);
		map.put("user", user.getId());
		map.put("type", request.getParameter("type"));
		OutAndInWarehouseOrder orders=wareHouseService.queryPutInOnlyOrders(map);
		if(null!=orders){
			orders.setAmount(Integer.parseInt(index));//设置当前第几页
		}
		ObjectMapper om = new ObjectMapper ();
		String result = om.writeValueAsString (orders);
		return result;
	}
	
	//入库暂时保存
	@RequestMapping(value={"inTemporarilySave"})
	@ResponseBody
	public String inTemporarilySave(OutAndInWarehouseOrder op,HttpServletRequest request,RedirectAttributes redirectAttributes) throws JsonProcessingException, ParseException{
		String time = op.getTime();
		
		if(null!=time&&!"".equals(time)){
			op.setTime(TimeUtils.EasyUITimeFormat(time));
		}
		try {
			wareHouseService.inTemporarilySave(op);
		} catch (Exception e) {
			logger.error("入库失败：", e);
			addMessage(redirectAttributes, "系统内部错误！");
			return "0";
		}
		return "1";
	}
	
	//查询针对当前用户是否存在未完成的订单
	@RequestMapping(value={"queryPersonalUnfinishedOrders"})
	@ResponseBody
	public String queryPersonalUnfinishedOrders(HttpServletRequest request) throws JsonProcessingException{
		//类型:入还是出
		String type = request.getParameter("type");
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("type", type);
		map.put("operator", UserUtils.getUser().getId());
		OutAndInWarehouseOrder orders=wareHouseService.queryPersonalUnfinishedOrders(map);
		ObjectMapper om = new ObjectMapper ();
		String result = om.writeValueAsString (orders);
		if(null!=result&&!"".equals(result)) 
		result = result.replaceAll("rep_Name", "text");
		
		return result;
	}
	
}
